<template>
	<view class="container">
		<view class="bg-set"></view>
		<view class="profile">
			<uni-card padding="0" spacing="0" margin="10rpx">
				<uni-list>
					<view class="header">
						<view style="font-size: 60rpx;margin-bottom: 20rpx;">￥ {{ sum }}</view>
						<!--        <view>订单15分钟未支付，将自动取消</view>
            <uni-countdown :show-day="false" :minute="15" :second="0" :font-size="20"></uni-countdown> -->
					</view>
					<!-- <uni-list-item title="订单编号">
            <template v-slot:footer>
              <view>{{ storeCart.cartObj.orderNo }}</view>
            </template>
          </uni-list-item> -->
					<uni-list-item title="下单时间">
						<template v-slot:footer>
							<view>{{ newDate() }}</view>
						</template>
					</uni-list-item>
				</uni-list>
			</uni-card>
			<uni-card padding="0" spacing="0" margin="10rpx">
				<uni-list>
					<view v-if="way == 'false'">
						<uni-list-item>
							<template v-slot:header>
								<view style="display: flex;align-items: center;">
									<view class="icon icon-weixin1"></view>
									<view style="margin-left: 10rpx;">微信支付</view>
								</view>
							</template>
							<template v-slot:footer>
								<radio checked="true" />
							</template>
						</uni-list-item>
					</view>
					<view v-else>
						<uni-list-item>
							<template v-slot:header>
								<view style="display: flex;align-items: center;">
									<view class="icon icon-huiyuan-copy-copy"></view>
									<view>
										<view style="margin-left: 10rpx;">余额支付</view>
										<view style="color: #5e93ff;">(餐补{{ store.profile?.subsidyAmount }})
											(余额{{ store.profile?.rechargeAmount }})</view>
									</view>
								</view>
							</template>
							<template v-slot:footer>
								<radio checked="true" />
							</template>
						</uni-list-item>
					</view>
				</uni-list>
			</uni-card>
			<view class="btn" @click="onPay">确认支付</view>
		</view>
	</view>
</template>

<script setup>
import loading from '../../components/loading.vue'
import { timeToTimestamp, timestampToTime } from '../../utils/data'
//  import global from '../../utils/websokect.js'//--------------------hsq修改

import {
	onLoad,
	onUnload
} from '@dcloudio/uni-app';
import {
	http
} from '../../utils/http';
import {
	nextTick,
	ref
} from 'vue';
import {
	useCartStore,
	useMemberStore,
} from '../../stores';
const storeCart = useCartStore()
const storeUser = useMemberStore()
const payMsg = ref()
const time = ref()

const obj = ref()
const store = useMemberStore()
const foodorderlist = ref([])
let sum = ref('') //支付金额
let way = ref() // 支付方式
let openId = ref()
let endTime = ref('')
let time3 = ref()
let time4 = ref()
let orderNoList = []//订单编号
let orderTradeNo = ref()//拉起支付信息订单编号
let Ordersdata = ref() // 微信支付信息
let clickStatus = true//按钮控制变量
onLoad((e) => {
	clickStatus = true
	endTime.value = e.endTime
	let kk = JSON.parse(e.orderList)
	orderNoList = kk.map(obj => obj.orderNo)
	obj.value = JSON.parse(e.payobj)
	sum.value = e.sum
	way.value = e.way
	openId.value = storeUser.profile?.openId

})
onUnload(() => {
	clearTimeout(time4.value)
})
// 新增订单
const addNewFoodOrders = async (type) => {
	const storeUser = useMemberStore()
	obj.value.forEach((item, index) => {
		let yuer = storeCart.cartObj.paymsg.filter(r => r.orderNo == item.orderNo)
		foodorderlist.value.push({
			"orderNo": item.orderNo,
			"orderTypeCode": "",
			"restaurantSerials": item.restaurantSerials,
			"restaurantName": storeCart.cartObj.restaurantName,
			"orderDate": storeCart.cartObj.orderDate,
			"orderCategorySerials": item.orderCategorySerials,
			"orderCategoryName": item.orderCategoryName,
			"totalAmount": item.defaultTotalAmount,
			"wxPayAmount": yuer.filter(r => r.payWayCode == 'WX').length > 0 ? yuer.filter(r =>
				r.payWayCode == 'WX')[0].paymentAmount : '0.00',
			"yePayAmount": yuer.filter(r => r.payWayCode == 'YE').length > 0 ? yuer.filter(r =>
				r.payWayCode == 'YE')[0].paymentAmount : '0.00',
			"cbPayAmount": yuer.filter(r => r.payWayCode == 'CB').length > 0 ? yuer.filter(r =>
				r.payWayCode == 'CB')[0].paymentAmount : '0.00',
			"addressSerials": storeUser.profile.addressSerials,
			"addressId": storeUser.profile.addressId,
			"addressLongName": storeUser.profile.addressTxt,
			"addressLevel": '',
			"customerId": storeUser.requestData.customerId,
			"customerName": storeUser.profile.customerName,
			"phoneNumber": storeUser.profile.phoneNumber,
			"notes": storeCart.cartObj.notes ? storeCart.cartObj.notes : '',
			foodpackagelist: item.foodpackagelist,
			foodlist: item.foodlist
		})
	})

	const res = await http({
		url: '/AddNewFoodOrders',
		method: 'post',
		data: {
			...storeUser.requestData,
			data: {
				foodorderlist: foodorderlist.value
			}
		}
	})
	let time1 = timeToTimestamp(endTime.value)//营业时间
	let time2 = timeToTimestamp(res.restime)//本地时间
	time3.value = time1 - time2
	if (!(time3.value > 0)) {
		uni.navigateBack({ delta: 4 })
		setTimeout(() => {
			uni.showToast({
				title: '餐厅营业结束，明天再来吧',
				icon: 'none',
				duration: 2000
			})
		}, 500)
		return
	}
	nextTick(async () => {
		if (res.errcode === 0 && type) {
			for (let i = 0; i < foodorderlist.value.length; i++) {
				const message = {
					ReqType: 'orderprint',
					ReqUser: openId.value, //患者id
					ReqData: foodorderlist.value[i].orderNo, //消息内容
					CheckData: openId.value,
					RcvUsers: ['wx']
				};
				// global.ws.send({
				// 	data: JSON.stringify(message)
				// });//--------------------hsq修改
				if (i == foodorderlist.value.length - 1 && type) {
					const store = useMemberStore()
					const res1 = await http({
						method: 'post',
						url: '/GetCustomersInfo',
						data: store.requestData
					})
					//  将获取到的用户信息存储仓库并直接跳转首页
					if (res1.data?.length > 0) {
						store.profile = {
							...store.profile,
							...res1.data[0]
						}
						const storeCart = useCartStore()
						storeCart.cart = []
						storeCart.cartNew = []
						clickStatus = false
						uni.hideLoading()
						uni.navigateBack({
							delta: 2
						})
						setTimeout(() => {
							uni.showToast({ title: '已完成支付', icon: 'success', duration: 1000 })
						}, 500)
					}

				}
			}
		} else if (res.errcode === 0) {
			nextTick(() => {
				clickStatus = false
				uni.hideLoading()
				wx.requestPayment({
					...Ordersdata.value.data,
					success: async (success) => {
						// 支付完成之后，新增订单并且将购物车相关数据置为空，同时跳转支付完成页面
						// addNewFoodOrders(false)
						const storeCart = useCartStore()
						storeCart.clearCart()
						setTimeout(() => {
							uni.showToast({ title: '支付完成', icon: 'success', duration: 2000 })
						}, 500)

						uni.navigateBack({
							delta: 2
						})
						// uni.navigateBack({url:'/pages/order_finish/order_finish'})
					},
					fail: (fail) => {
						uni.navigateBack({
							delta: 4
						})
					},
					complete: (complete) => {
						console.log('成功');
					}
				})
			})
		} else {

			console.log(res, '判断错误');
			setTimeout(() => {
				uni.showToast({ title: '新增订单异常', icon: 'none' })
			}, 500)
			uni.navigateBack({
				delta: 4
			})
		}
	})

}
// 订单支付
const pay = async () => {
	const storeCart = useCartStore()
	const {
		data, restime, errcode
	} = await http({
		url: '/CreatePayForOrder',
		method: 'post',
		data: {
			...storeUser.requestData,
			data: [
				...storeCart.cartObj.paymsg
			]
		}
	})
	orderTradeNo.value = data.tradeNo
	Ordersdata.value = data
	nextTick(() => {
		if (errcode == 0) {
			let time1 = timeToTimestamp(endTime.value)//营业时间
			let time2 = timeToTimestamp(restime)//本地时间
			time3.value = time1 - time2
			if (!time3.value > 0) {

				uni.showToast({
					title: '餐厅营业结束，明天再来吧',
					icon: 'none',
					duration: 2000
				})
				setTimeout(() => {
					uni.navigateBack({ delta: 4 })
				}, 1500)


			} else {
				time4.value = setTimeout(async () => {
					const res = await http({
						url: '/ClosePayForOrders',
						method: 'post',
						data: {
							...storeUser.requestData,
							data: {
								orderNo: orderNoList,
								tradeNo: orderTradeNo.value
							}
						}
					})
				}, time3.value)
			}
			addNewFoodOrders(false)
		}
	})
}

// 提交订单
const onPay = () => {
	if (clickStatus) {
		uni.showLoading({
			title: '加载中',
			mask: true
		})
		clearTimeout(time.value);
		time.value = setTimeout(async () => {
			if (way.value == 'false') {
				pay()
			} else {
				addNewFoodOrders(true)
			}
		}, 200)
	}


}

const newDate = () => {
	const Data = new Date()
	const nry = Data.getFullYear() + '-' + (('0' + (Data.getMonth() + 1)).slice(-2)) + '-' + (('0' + (Data
		.getDate())).slice(-2))
	const sfm = (('0' + (Data.getHours())).slice(-2)) + ':' + (('0' + Data.getMinutes()).slice(-2))
	return nry + ' ' + sfm
}

</script>

<style scoped lang="scss">
.profile {
	height: 130rpx;
	padding: 85rpx 0;
	border-radius: 0 0 40rpx 50rpx;
	background-color: #0081ff;
}

.bg-set {
	position: fixed;
	width: 100%;
	height: 100%;
	top: 0;
	left: 0;
	background-color: #f4f4f4;
	z-index: -1;
}

.header {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	margin: 30rpx 0 0;
}

.btn {
	position: fixed;
	bottom: 0;
	left: 0;
	padding: 0;
	width: 100%;
	// height: 80rpx;
	line-height: calc(80rpx + env(safe-area-inset-bottom) / 2);
	text-align: center;
	background-color: #0081ff;
	color: #fff;
	height: calc(80rpx + env(safe-area-inset-bottom) / 2);
	padding-bottom: calc(env(safe-area-inset-bottom) / 2);
	box-shadow: -5rpx -4rpx 5px 0rpx rgba(0, 0, 0, 0.5);
}
</style>